#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PyInstaller hook for onnxruntime
解决onnxruntime打包时的动态库和依赖问题
"""

from PyInstaller.utils.hooks import collect_data_files, collect_submodules, collect_dynamic_libs
import os

# 收集onnxruntime的所有数据文件
datas = collect_data_files('onnxruntime')

# 收集onnxruntime的动态库
binaries = collect_dynamic_libs('onnxruntime')

# 收集onnxruntime的所有子模块
hiddenimports = collect_submodules('onnxruntime')

# 添加额外的隐藏导入
hiddenimports.extend([
    'onnxruntime.capi',
    'onnxruntime.capi.onnxruntime_pybind11_state',
    'onnxruntime.capi._pybind_state',
    'onnxruntime.backend',
    'onnxruntime.backend.backend',
])

# 手动添加onnxruntime的关键文件
try:
    import onnxruntime
    onnx_path = os.path.dirname(onnxruntime.__file__)
    
    # 查找关键的动态库文件
    for root, dirs, files in os.walk(onnx_path):
        for file in files:
            if file.endswith(('.dll', '.so', '.dylib', '.pyd')):
                full_path = os.path.join(root, file)
                rel_path = os.path.relpath(full_path, onnx_path)
                binaries.append((full_path, os.path.join('onnxruntime', os.path.dirname(rel_path))))
                print(f"添加onnxruntime动态库: {file}")
                
except ImportError:
    print("警告: 无法导入onnxruntime，跳过手动文件收集")
except Exception as e:
    print(f"收集onnxruntime文件时出错: {e}")

print(f"onnxruntime hook: 收集到 {len(datas)} 个数据文件")
print(f"onnxruntime hook: 收集到 {len(binaries)} 个二进制文件")
print(f"onnxruntime hook: 收集到 {len(hiddenimports)} 个隐藏导入")
